using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using WorkFlowCore.BusinessDemo.Web.Models.AdapterDtos;

namespace WorkFlowCore.BusinessDemo.Web.Services.Adapters
{
    public class WorkTaskAdapterService : IWorkTaskAdapterService
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IConfiguration _configuration;
        private readonly ILogger<WorkTaskAdapterService> _logger;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public WorkTaskAdapterService(
            IHttpClientFactory httpClientFactory,
            IConfiguration configuration,
            ILogger<WorkTaskAdapterService> logger,
            IHttpContextAccessor httpContextAccessor)
        {
            _httpClientFactory = httpClientFactory;
            _configuration = configuration;
            _logger = logger;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 获取应用程序ID，从配置文件中读取，如果未配置则使用默认值
        /// </summary>
        /// <returns>应用程序ID</returns>
        private string GetAppId()
        {
            return _configuration["WorkFlowCore:AppId"] ?? "BusinessDemo";
        }

        public async Task<WorkTaskDto> GetWorkTaskByEntityInfoAsync(GetWorkTaskByEntityInfoInputDto input)
        {
            try
            {
                var baseUrl = _configuration["WorkFlowCore:HostBaseUrl"];
                var client = _httpClientFactory.CreateClient();
                var url = $"{baseUrl}/api/WorkTask/GetWorkTaskByEntityInfo?appid={GetAppId()}&entityFullName={input.EntityFullName}&entityKeyValue={input.EntityKeyValue}";

                var authCookie = _httpContextAccessor.HttpContext?.Request.Cookies["AuthCookie"];
                if (!string.IsNullOrEmpty(authCookie))
                {
                    client.DefaultRequestHeaders.Add("ThirdpartAuthorization", $"Bearer {authCookie}");
                }
                
                var response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                
                var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<WorkTaskDto>>();
                if (apiResponse != null && apiResponse.Code == "success" && apiResponse.Data != null)
                {
                    return apiResponse.Data;
                }
                else
                {
                    var errorMessage = $"Error getting work task by entity info. Code: {apiResponse?.Code}, Message: {apiResponse?.Msg}";
                    _logger.LogError(errorMessage);
                    throw new HttpRequestException(errorMessage ?? "Failed to get work task by entity info due to API error.");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting work task by entity info");
                throw;
            }
        }

        public async Task<WorkTaskDto> CreateWorkTaskWithDefaultVersionAsync(CreateWorkTaskWithDefaultVersionInputDto input)
        {
            try
            {
                var baseUrl = _configuration["WorkFlowCore:HostBaseUrl"];
                var client = _httpClientFactory.CreateClient();
                var url = $"{baseUrl}/api/WorkTask/CreateWorkTaskWithDefaultVersionByNo?appid={GetAppId()}";

                var authCookie = _httpContextAccessor.HttpContext?.Request.Cookies["JwtToken"];
                if (!string.IsNullOrEmpty(authCookie))
                {
                    client.DefaultRequestHeaders.Add("ThirdpartAuthorization", authCookie);
                }
                
                var response = await client.PostAsJsonAsync(url, input);
                response.EnsureSuccessStatusCode();
                
                var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<WorkTaskDto>>();
                if (apiResponse != null && apiResponse.Code == "success" && apiResponse.Data != null)
                {
                    return apiResponse.Data;
                }
                else
                {
                    var errorMessage = $"Error creating work task with default version. Code: {apiResponse?.Code}, Message: {apiResponse?.Msg}";
                    _logger.LogError(errorMessage);
                    throw new HttpRequestException(errorMessage ?? "Failed to create work task with default version due to API error.");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating work task with default version");
                throw;
            }
        }

        public async Task<StartWorkTaskOutputDto> StartWorkTaskAsync(StartWorkTaskInputDto input)
        {
            try
            {
                var baseUrl = _configuration["WorkFlowCore:HostBaseUrl"];
                var client = _httpClientFactory.CreateClient();
                var url = $"{baseUrl}/api/WorkTask/StartWorkTask?appid={GetAppId()}";

                var authCookie = _httpContextAccessor.HttpContext?.Request.Cookies["JwtToken"];
                if (!string.IsNullOrEmpty(authCookie))
                {
                    client.DefaultRequestHeaders.Add("ThirdpartAuthorization", authCookie);
                }
                
                var response = await client.PostAsJsonAsync(url, input);
                response.EnsureSuccessStatusCode();
                
                var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<StartWorkTaskOutputDto>>();
                if (apiResponse != null && apiResponse.Code == "success" && apiResponse.Data != null)
                {
                    return apiResponse.Data;
                }
                else
                {
                    var errorMessage = $"Error starting work task. Code: {apiResponse?.Code}, Message: {apiResponse?.Msg}";
                    _logger.LogError(errorMessage);
                    throw new HttpRequestException(errorMessage ?? "Failed to start work task due to API error.");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error starting work task");
                throw;
            }
        }

        public async Task<List<WorkTaskDto>> GetAllProcessingWorkTasksByEntityTypeAsync(GetAllProcessingWorkTasksByEntityTypeInputDto input)
        {
            try
            {
                var baseUrl = _configuration["WorkFlowCore:HostBaseUrl"];
                var client = _httpClientFactory.CreateClient();
                var queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
                queryString["appid"] = GetAppId();
                queryString["entityFullName"] = input.EntityFullName;
                if (input.EntityKeyValues != null)
                {
                    foreach (var keyValue in input.EntityKeyValues)
                    {
                        queryString.Add("entityKeyValues", keyValue);
                    }
                }
                var url = $"{baseUrl}/api/WorkTask/GetAllProcessingWorkTasksByEntityType?{queryString}";

                var authCookie = _httpContextAccessor.HttpContext?.Request.Cookies["JwtToken"];
                if (!string.IsNullOrEmpty(authCookie))
                {
                    client.DefaultRequestHeaders.Add("ThirdpartAuthorization", $"Bearer {authCookie}");
                }

                _logger.LogInformation("Sending HTTP request for GetAllProcessingWorkTasksByEntityTypeAsync. Method: GET, URL: {Url}", url);
                var response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                
                var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<List<WorkTaskDto>>>();
                if (apiResponse != null && apiResponse.Code == "success" && apiResponse.Data != null)
                {
                    return apiResponse.Data;
                }
                else
                {
                    var errorMessage = $"Error getting processing work tasks by entity type. Code: {apiResponse?.Code}, Message: {apiResponse?.Msg}";
                    _logger.LogError(errorMessage);
                    throw new HttpRequestException(errorMessage ?? "Failed to get processing work tasks by entity type due to API error.");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting processing work tasks by entity type");
                throw;
            }
        }
    }
}
